package com.mo.xi.ge.info.loc

import android.Manifest
import android.content.Context
import android.location.Location
import android.util.Log
import androidx.annotation.RequiresPermission


/**
 * data:2024/01/25
 */
object LocationWrapper {

    private const val TAG = "debug_OLocationManager"

    private var locationService: LocationManager? = null
    var applicationContext: Context? = null

    @RequiresPermission(allOf = [Manifest.permission.ACCESS_COARSE_LOCATION])
    fun create(context: Context) {
        val ctx = context.applicationContext
        applicationContext = ctx
        if (locationService == null) {
            locationService = LocationManager(ctx)
        }
        locationService?.startLocation()
    }

    fun stop() {
        locationService?.stopLocation()
    }

    /**
     * 只获取一次回调，优先读取缓存
     */
    fun getOnceLocationCallback(callback: (Location?) -> Unit) {
        requestOnceCallbackLocation(callback)
    }

    @RequiresPermission(allOf = [Manifest.permission.ACCESS_COARSE_LOCATION])
    fun requestLocationUpdates() {
        requestLocation { }
    }

    fun getLastLocation(): Location? {
        return locationService?.getReqLastLocation()
    }

    @RequiresPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
    fun getNewLast(): Location? {
        val location = locationService?.getLastOneInfo()
        if (location == null || location.latitude == 0.0 || location.longitude == 0.0) {
            return CacheLocation.getCache()
        }
        return location
    }


    @Synchronized
    private fun requestOnceCallbackLocation(callback: (Location?) -> Unit) {
        if (locationService != null) {
            callback.invoke(locationService?.getReqLastLocation())
        }
        locationService?.reqLocationOne(callback)
    }

    @Synchronized
    private fun requestLocation(callback: (Location?) -> Unit) {
        if (locationService == null) {
            Log.d(TAG, "no location service available")
            callback.invoke(locationService?.getReqLastLocation())
        }
        locationService?.reqLocation(callback)
    }
}
